// utils/websocket.js
class WebSocketService {
  constructor(url) {
    this.url = url
    this.socket = null
    this.onMessageCallback = null
    this.connect()
  }

  connect() {
    this.socket = new WebSocket(this.url)

    this.socket.onopen = () => {
      console.log('WebSocket 已连接')
    }

    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data)
      if (this.onMessageCallback) {
        this.onMessageCallback(data)
      }
    }

    this.socket.onclose = () => {
      console.log('WebSocket 已关闭，尝试重连...')
      setTimeout(() => this.connect(), 3000) // 3秒后重连
    }

    this.socket.onerror = (error) => {
      console.error('WebSocket 错误:', error)
    }
  }

  send(data) {
    if (this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(data))
    } else {
      console.warn('WebSocket 未连接，无法发送')
    }
  }

  onMessage(callback) {
    this.onMessageCallback = callback
  }

  close() {
    if (this.socket) {
      this.socket.close()
    }
  }
}

// 单例模式，确保全局只有一个连接
const wsService = new WebSocketService('ws://localhost:8080')
export default wsService
